from google.appengine.ext import db
from exceptions import *

class AziendaData(db.Model):
	name = db.StringProperty("")
	address = db.PostalAddressProperty("")
	piva = db.StringProperty("")
	user = db.UserProperty()
	eur_h = db.FloatProperty(0)
	last_operation = db.DateTimeProperty(auto_now=True)
	deleted = db.BooleanProperty(default=False)

	street = db.StringProperty("")
	zipCode = db.StringProperty("")
	city = db.StringProperty("")

	#name_lower = ndb.ComputedProperty(lambda self: self.name.lower())
	
	@staticmethod
	def getSingleCustomerRawData(user, key):
		customer = db.get(key)
		print customer
		#if customer and user==customer.user:
		#	return customer
		#return None

	@staticmethod
	def createAziendaData(user, key=None, name=None, address=None, piva="", eur_h=0, **trash):
		print "creating or modifing azienda with key=%s name=%s address=%s piva=%s eur_h=%s" % (key, name, address, piva, eur_h)
		aziendadatadb, new = key and (db.get(key), False) or (AziendaData(), True)
		aziendadatadb.user = user
		if name:
			aziendadatadb.name = name
		if name=='':
			raise NoNameAziendaException()
		#if address:
		#	aziendadatadb.address = address
		if piva:
			aziendadatadb.piva = piva
		if eur_h:
			aziendadatadb.eur_h = float(eur_h)
		if address:
			aziendadatadb.street = address['street']
			aziendadatadb.zipCode = address['zipCode']
			aziendadatadb.city = address['city']
		aziendadatadb.put()
		return aziendadatadb.myserialize(), new
	
	@staticmethod
	def getAziendaData(user=None, name=None, address=None, piva=None, eur_h=None, small=False, **trash):
		#if small:
		#	lst = db.Query(AziendaData, projection=('key', 'name'))
		#else:
		lst = AziendaData.all().filter("deleted =", False).order("name")
		if user:
			lst = lst.filter('user', user)
		if name:
			lst = lst.filter('name', name)
		if address:
			lst = lst.filter('address', address)
		if piva:
			lst = lst.filter('piva', piva)
		if eur_h:
			lst = lst.filter('eur_h', eur_h)
		
		if small:
			#print map(lambda az: az.myserializeSmall(), lst.fetch(None))
			#return map(lambda az: az.myserializeSmall(), lst)
			return map(lambda az: az.myserialize(), lst)
		else:
			return map(lambda az: az.myserialize(), lst)
	
	@staticmethod
	def deleteAziendaData(key=None, **trash):
		#print "elimino con key="+str(key)
		if key:
			#db.get(key).delete()
			model = db.get(key)
			model.deleted = True
			model.put()
		else:
			raise MyException("Inexistent key")
	
	def myserialize(self):
		return {
				'key':str(self.key()),
				'name':self.name,
				#'address':self.address,
				'address': {
					'street':self.street,
					'zipCode':self.zipCode,
					'city': self.city
				},
				'piva':self.piva,
				'eur_h':self.eur_h,
				'last_operation':self.last_operation.isoformat()
			}

	def myserializeSmall(self):
		return {
				'key':str(self.key()),
				'name':self.name
			}